package com.tianshi.pxx.service.impl;


import com.tianshi.pxx.mapper.CartMapper;
import com.tianshi.pxx.mapper.OrdersMapper;
import com.tianshi.pxx.pojo.entity.Product;
import com.tianshi.pxx.pojo.vo.ProductVO;
import com.tianshi.pxx.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /*
     * 查询用户的所有订单
     * */
    @Override
    @Cacheable(value = "orders-all", key = "#id") //orders::2  zget orders::2
    public List<Product> list(Integer id) {
        //根据用户查询,当前用户的所有订单
        //将订单中外键为user_id=id的,然后连接查询商品信息
        List<Product> res = ordersMapper.list(id);
        log.info("OrdersServiceImpl.list  res:{}", res);
        return res;
    }


    /*
     * 根据商品名称搜索商品
     * */
    @Override
    @Cacheable(value = "orders-searchByName", key = "#productName+#id")
    public List<Product> searchByName(String productName, Integer id) {
        //根据商品名称搜索商品
        //先查询商品的id
        //select product_id from orders where user_id=#{id} and name like concat('%',#{productName},'%')
        //在通过商品信息查询商品信息
        return ordersMapper.searchByName(productName, id);
    }

    @Override
    public void deleteById(Integer id) {
        //删除订单信息
        //delete from orders where id=#{id}
        //删除redis缓存
        redisTemplate.delete(deleteKeys("orders*"));
        log.info("OrdersServiceImpl.deleteById  id:{}", id);
        ordersMapper.deleteById(id);
    }



    /*
    * 根据模式串获取redis缓存的key值
    * */
    private Set<String> deleteKeys(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        return keys;
    }
}
